package com.eshop.utils.location;

import com.alibaba.fastjson.JSONObject;
import cn.hutool.http.HttpUtil;
import com.eshop.exception.BadRequestException;
import cn.hutool.core.util.StrUtil;
import com.eshop.utils.RedisUtil;
import com.eshop.utils.ShopKeyUtils;
import cn.hutool.core.util.NumberUtil;

public class LocationUtils
{
    private static double EARTH_RADIUS;
    private static final String QQ_MAP_URL = "https://apis.map.qq.com/ws/geocoder/v1/";
    
    private static double rad(final double d) {
        return d * 3.141592653589793 / 180.0;
    }
    
    public static double getDistance(final double lat1, final double lng1, final double lat2, final double lng2) {
        final double radLat1 = rad(lat1);
        final double radLat2 = rad(lat2);
        final double a = radLat1 - radLat2;
        final double b = rad(lng1) - rad(lng2);
        double s = 2.0 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2.0), 2.0) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2.0), 2.0)));
        s *= LocationUtils.EARTH_RADIUS;
        s = Math.round(s * 10000.0) / 10000.0;
        return NumberUtil.round(s, 2).doubleValue();
    }
    
    public static GetTencentLocationVO getLocation(final String addr) {
        final String key = RedisUtil.get(ShopKeyUtils.getTengXunMapKey());
        if (StrUtil.isBlank((CharSequence)key)) {
            throw new BadRequestException("请先配置腾讯地图key");
        }
        final String url = StrUtil.format((CharSequence)"?address={}&key={}", new Object[] { addr, key });
        final String json = HttpUtil.get("https://apis.map.qq.com/ws/geocoder/v1/" + url);
        return (GetTencentLocationVO)JSONObject.parseObject(json, (Class)GetTencentLocationVO.class);
    }
    
    static {
        LocationUtils.EARTH_RADIUS = 6378.137;
    }
}
